const {user}=require("../model/index")
const { Op } = require("sequelize");
class UserService{
    async CreateUser(username, phone, password) {
        try {
            await user.create({
                username,
                phone,
                password
            })
        } catch (error) {
            console.log(error)
        }
    }
    async ModifyInfo(id, username, address) {
        try {
            await user.update({
                username,
                address,
            }, {
                where: {
                    id
                }
            })
        } catch (error) {
            console.log(error)
        }
    }
    async getUserByPhone(phone) {
        try {
            let res=await user.findAll({
                where: {
                    phone
                }
            })
            return res
        } catch (error) {
            console.log(error)
        }
    }
    async getUserByName(username) {
        try {
            let res=await user.findAll({
                where: {
                    username
                }
            })
            return res
        } catch (error) {
            console.log(error)
        }
    }
    /**
     * 
     * @returns 
     */
    //后台管理系统
     //获取所有用户的数据
     async getUsers() {
        try {
            let res=await user.findAll({})
            return res
        } catch (error) {
            console.log(error)
        }
    }
    //根据id获取用户的数据
    async getUserById(id) {
        try {
            let res = await user.findAll({
                where: {
                    id
                }
            })
            return res
        } catch (error) {
            console.log(error)
        }
    }
    //根据id删除用户
    async deleteUserById(id) {
        try {
            let res = await user.destroy({
                where: {
                    id
                }
            })
            return res
        } catch (error) {
            console.log(error)
        }
    }
    async ModifyUserRoleById(id,role_name) {
        try {
            await user.update({
                role_name
            }, {
                where: {
                    id
                }
            })
        } catch (error) {
            console.log(error)
        }
    }
    async getUserByName(keyValue) {
        if (!keyValue) {
            let res = await user.findAll()
            return res
        }
        let res = await user.findAll({
            where: {
                [Op.or]: {
                    username: {
                        [Op.substring]: keyValue,  
                    },
                    phone: {
                        [Op.substring]: keyValue,  
                    }
                }
                
            }
        })
        return res
    }
}
module.exports=new UserService()